package org.buptsse.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.buptsse.entity.HistoryItem;
import org.buptsse.entity.User;
import org.buptsse.listview.HistoryBuyInPage;
import org.buptsse.listview.HistorySoldOutPage;
import org.buptsse.listview.TradeUndonePage;
import org.buptsse.listview.TradedonePage;
import org.buptsse.page.MyInfoPage;
import org.buptsse.page.MyPasswordPage;
import org.buptsse.page.MyPhotoPage;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class TradeHistoryActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private ViewPager viewPager = null;
	private User user = null;
	private String search = null;

	public final static int LoadFinish = 1;
	public final static int LoadError=2;
	public final static int NetError=3;
	public final static int NoData=4;
	private final static int BuyInPage=1,SellOutPage=2;
	
	private int currentPage=BuyInPage;
	private HistorySoldOutPage historySoldOutPage = null;
	private HistoryBuyInPage historyBuyInPage = null;
	private Button backButton = null;
	private Button refreshButton=null;
	private EditText searchText = null;
	private RadioButton a = null;
	private RadioButton b = null;
	private boolean isBuyInLoaded=false,isSellOutLoaded=false;
	private ProgressDialog pDialog;
	
	private Handler THAhandler=new Handler()
	{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.what==APPConstant.dismissProgressDialog)
			{
				pDialog.dismiss();
			}
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ltrade_history);
		
		//刷新按钮
		refreshButton=(Button) findViewById(R.id.refresh_button);
		refreshButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(currentPage==BuyInPage)
				{
					//加载买入数据
					Thread thread=new Thread(new myThread(BuyInPage,( (MyPagerAdapter)viewPager.getAdapter()).getPage(0).getHandler()));
					thread.start();
				}
				else if(currentPage==SellOutPage)
				{
					//加载卖出数据
					Thread thread=new Thread(new myThread(SellOutPage,( (MyPagerAdapter)viewPager.getAdapter()).getPage(1).getHandler()));
					thread.start();
				}
			}
		});
		
		historySoldOutPage = new HistorySoldOutPage(this, user);
		historyBuyInPage = new HistoryBuyInPage(this, user);

		backButton = (Button) this.findViewById(R.id.bt_back);

		backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent it = new Intent();
				it.putExtra("user", user);
				TradeHistoryActivity.this.setResult(RESULT_OK, it);
				TradeHistoryActivity.this.finish();
			}
		});

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		MyPagerAdapter adapter = new MyPagerAdapter(this);
		viewPager.setAdapter(adapter);
		RadioGroup radioGroup = (RadioGroup) this
				.findViewById(R.id.rg_search_result_btns);
		// here is the tab to be ture
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rd_buy_in:
					viewPager.setCurrentItem(0);
					break;
				case R.id.rd_sold_out:
					viewPager.setCurrentItem(1);
					break;
				default:
					break;
				}
			}
		});
		a = (RadioButton)this.findViewById(R.id.rd_buy_in);
		b = (RadioButton)this.findViewById(R.id.rd_sold_out);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int page) {
				if(page==0){
					a.setChecked(true);
					currentPage=BuyInPage;
					if(isBuyInLoaded==false)
					{
						//加载买入数据
						loading("正在加载...");
						Thread thread=new Thread(new myThread(BuyInPage,( (MyPagerAdapter)viewPager.getAdapter()).getPage(0).getHandler()));
						thread.start();
					}
				}
				if(page==1){
					b.setChecked(true);
					currentPage=SellOutPage;
					if(isSellOutLoaded==false)
					{
						//加载卖出数据
						loading("正在加载...");
						Thread thread=new Thread(new myThread(SellOutPage,( (MyPagerAdapter)viewPager.getAdapter()).getPage(1).getHandler()));
						thread.start();
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		
		//加载买入数据
		loading("正在加载...");
		Thread thread=new Thread(new myThread(BuyInPage,( (MyPagerAdapter)viewPager.getAdapter()).getPage(0).getHandler()));
		thread.start();
	}

	
	public void loading(String msg){
		pDialog = new ProgressDialog(this); 
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
    }
	
	private class MyPagerAdapter extends PagerAdapter {

		private ArrayList<LinearLayout> views;

		public MyPagerAdapter(Context context) {
			views = new ArrayList<LinearLayout>();
			views.add(historyBuyInPage);
			views.add(historySoldOutPage);

		}
		
		public LinearLayout getPage(int index)
		{
			return views.get(index);
		}

		@Override
		public void destroyItem(View view, int arg1, Object object) {
			((ViewPager) view).removeView((LinearLayout) object);
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public Object instantiateItem(View view, int position) {
			View myView = views.get(position);
			((ViewPager) view).addView(myView);
			return myView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {

		}
	}
private class myThread implements Runnable {
		
		private boolean isRun=false;
		private Handler myHandler;
		private int dataKind;
		
		public myThread(int dataKind,Handler handler)
		{
			this.myHandler=handler;
			this.dataKind=dataKind;
		}
		
		public boolean IsRun()
		{
			return isRun;
		}
		
		@SuppressWarnings("unchecked")
		@Override
		public void run() {
			isRun=true;
			//在这里获取买入的记录
			if(ConnectionChecker.isNetworkAvailable(getApplicationContext())==false)
			{
				Message msg=myHandler.obtainMessage(TradeHistoryActivity.NetError);
				myHandler.sendMessage(msg);
				isRun=false;
				Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
				THAhandler.sendMessage(msg2);
				return;
			}
			String name=GloableInstance.user.getName();
			String role=(dataKind==BuyInPage)?"buyer":"seller";
			String url=APPConstant.getHistoryUrl+"?username="+name+"&role="+role;
			HttpGet httpGet=new HttpGet(url);
			try {
				HttpResponse response=new DefaultHttpClient().execute(httpGet);
				if(response.getStatusLine().getStatusCode() == 200)    
				{
					String strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
					//Log.v("load buy in",strResult);
					if(strResult.contains("nodata"))
					{
						Message msg=myHandler.obtainMessage(TradeHistoryActivity.NoData);
						myHandler.sendMessage(msg);
						isRun=false;
						Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
						THAhandler.sendMessage(msg2);
						return;
					}else if(strResult.contains("failure")){
						Message msg=myHandler.obtainMessage(TradeHistoryActivity.LoadError);
						myHandler.sendMessage(msg);
						isRun=false;
						Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
						THAhandler.sendMessage(msg2);
						return;
					}else{
						List<HistoryItem> resultList=(List<HistoryItem>) JsonUtils.getJsonObject(strResult, new TypeToken<LinkedList<HistoryItem>>() {}.getType());
						//System.out.println("=====list size is:"+historyBuyInList.size());
						Message msg=myHandler.obtainMessage(TradeHistoryActivity.LoadFinish);
						msg.obj=resultList;
						myHandler.sendMessage(msg);
						if(dataKind==BuyInPage)
							isBuyInLoaded=true;
						else {
							isSellOutLoaded=true;
						}
						isRun=false;
						Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
						THAhandler.sendMessage(msg2);
						return;
					}
				}else {
					Message msg=myHandler.obtainMessage(TradeHistoryActivity.LoadError);
					myHandler.sendMessage(msg);
					isRun=false;
					Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
					THAhandler.sendMessage(msg2);
					return;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Message msg=myHandler.obtainMessage(TradeHistoryActivity.LoadError);
				myHandler.sendMessage(msg);
				Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
				THAhandler.sendMessage(msg2);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Message msg=myHandler.obtainMessage(TradeHistoryActivity.LoadError);
				myHandler.sendMessage(msg);
				Message msg2=THAhandler.obtainMessage(APPConstant.dismissProgressDialog);
				THAhandler.sendMessage(msg2);
			}
		}
	}
}